package com.atbun.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.atbun.commonutils.R;
import com.atbun.vod.service.VodService;
import com.atbun.vod.utils.AliyunVodSDKUtils;
import com.atbun.vod.utils.ConstantPropertiesUtil;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @Description : 阿里云视频点播微服务
 * @Author : mayp
 * @Date: 2020-05-11 22:26
 */
@RestController
@RequestMapping("/eduvod/video")
public class VodController {
    @Autowired
    private VodService vodService;

    /**
     * 上传视频到阿里云
     * @return
     */
    @PostMapping("uploadVideo")
    public R uploadVideo(MultipartFile file){
        String videoId = this.vodService.uploadVideo(file);

        if (null != videoId){
            return R.ok().message("视频上传成功").data("videoId", videoId);
        }
        return R.ok().message("视频上传失败");
    }

    /**
     * 根据云端视频id删除视频信息
     * @param videoId
     * @return
     */
    @DeleteMapping("deleteVideo/{videoId}")
    public R deleteVideo(
            @ApiParam(name = "videoId", value = "云端视频id", required = true)
            @PathVariable String videoId){
        this.vodService.deleteVideoByVideoId(videoId);
        return R.ok().message("视频删除成功");
    }

    /**
     * 根据多个云视频删除信息
     * @param videoIdList
     * @return
     */
    @DeleteMapping("deleteVideoList")
    public R deleteVideoList(@RequestParam("videoIdList") List<String> videoIdList){
        this.vodService.removeMoreAlyVideo(videoIdList);
        return R.ok().message("视频删除成功");
    }

    /**
     * 视频点播 功能
     * @param videoId
     * @return
     * @throws Exception
     */
    @GetMapping("getPlayAuth/{videoId}")
    public R getVideoPlayAuth(@PathVariable("videoId") String videoId) throws Exception {
        //获取阿里云存储相关常量
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;

//        初始化
        DefaultAcsClient client = AliyunVodSDKUtils.initVodClient(accessKeyId,accessKeySecret);
//        请求
        GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
        request.setVideoId(videoId);

        //响应
        GetVideoPlayAuthResponse response = client.getAcsResponse(request);

        //得到播放凭证
        String playAuth = response.getPlayAuth();

        //返回结果
        return R.ok().message("获取凭证成功").data("playAuth", playAuth);

    }

}
